﻿using System;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.Infrastructure.Base;
using ZilLion.Service.Core.Log;
using ZilLion.Service.TaskPlatform.Domain.Response;
using ZilLion.Service.TaskPlatform.Domain.Respository.Interface;

namespace ZilLion.Service.TaskPlatform.Controllers
{
    /// <summary>
    ///     任务包上传
    /// </summary>
    [Route("Api/TaskPlatform/UploadTaskPackage")]
    [AllowAnonymous]
    public class TaskPackageUploadController : ZilLionControllerBase
    {
        
        private readonly ITaskPackageRespository _taskMongoGridFsRespository;
        public TaskPackageUploadController(ITaskPackageRespository taskMongoGridFsRespository)
        {
            _taskMongoGridFsRespository = taskMongoGridFsRespository;
        }

        private byte[] StreamToBytes(Stream stream)
        {
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        ///     上传Task插件包
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("Upload")]
        public UploadTaskPackageResponse UploadTaskPackage()
        {
            var files = Request.Form.Files;
            foreach (var file in files)
            {
                if (file == null) continue;
                var filename = ContentDispositionHeaderValue
                    .Parse(file.ContentDisposition)
                    .FileName
                    .Trim('"');
                var filestream = file.OpenReadStream();
                var fileid = Guid.NewGuid().ToString("N");
                var fileInfo = new FileInfo(filename);
                var fileName = fileInfo.Name.Replace(fileInfo.Extension, string.Empty).ReplaceLast(".", string.Empty);
                try
                {
                 var savedfilecrc=_taskMongoGridFsRespository.UploadFileToGridFs(filestream,
                        fileid);
                    return new UploadTaskPackageResponse
                    {
                        PackageKey = fileid,
                        FileName = fileName,
                        FileCrc = savedfilecrc
                    };
                }
                catch (Exception e)
                {
                    ZilLionLogManager.Instance().Error(e);
                }
            }
            return new UploadTaskPackageResponse();
        }
    }
}